package com.auroramanito.uaa.validation;

import com.auroramanito.uaa.annotation.ValidPassword;
import lombok.RequiredArgsConstructor;
import lombok.val;
import org.passay.*;
import org.passay.spring.SpringMessageResolver;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Arrays;

@RequiredArgsConstructor
public class PasswordConstraintValidator implements ConstraintValidator<ValidPassword,String> {

    private final SpringMessageResolver springMessageResolver;

    @Override
    public void initialize(ValidPassword constraintAnnotation) {

    }

    @Override
    public boolean isValid(String password, ConstraintValidatorContext context) {
        val validator = new PasswordValidator(springMessageResolver,Arrays.asList(
                new LengthRule(8,30),  //密码长度 8-30
                new CharacterRule(EnglishCharacterData.UpperCase,1),    //含一位大写
                new CharacterRule(EnglishCharacterData.LowerCase,1),    //含一位小写
                new CharacterRule(EnglishCharacterData.Special,1),      //含一位特殊字符
                new IllegalSequenceRule(EnglishSequenceData.Alphabetical,5,false),//禁止5个连续字符 abcde
                new IllegalSequenceRule(EnglishSequenceData.Numerical,5,false),//禁止5个连续数字12345
                new IllegalSequenceRule(EnglishSequenceData.USQwerty,5,false),//禁止键盘的连续5个数字 qwert
                new WhitespaceRule() //禁止空格

        ));
        val result = validator.validate(new PasswordData(password));
        context.disableDefaultConstraintViolation();
        context.buildConstraintViolationWithTemplate(String.join(",",validator.getMessages(result))).addConstraintViolation();
        return result.isValid();
    }
}
